package org.jeecg.modules.content.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xkcoding.http.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.content.entity.ConContentTemplate;
import org.jeecg.modules.content.entity.ContentGoto;
import org.jeecg.modules.content.entity.ContentInfo;
import org.jeecg.modules.content.service.IConContentTemplateService;
import org.jeecg.modules.content.service.IContentGotoService;
import org.jeecg.modules.content.service.IContentInfoService;
import org.jeecg.modules.task.entity.TaskInfoBase;
import org.jeecg.modules.task.entity.TaskWorkflowStep;
import org.jeecg.modules.task.service.ITaskOperationService;
import org.jeecg.modules.task.service.ITaskWorkflowStepService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* @Description: 内容信息
* @Author: wufanxin
* @Date:   2020-06-28
* @Version: V1.0
*/
@Slf4j
@Api(tags="内容信息")
@RestController
@RequestMapping("/content/contentInfo")
public class ContentInfoController extends JeecgController<ContentInfo, IContentInfoService> {

   @Autowired
   private IContentInfoService conContentInfoService;

   @Autowired
   private ITaskWorkflowStepService stepService;

    @Autowired
    IConContentTemplateService templateService;

    @Autowired
    ITaskOperationService operationService;

    @Autowired
    IContentGotoService contentGotoService;
    /**
     * 内容信息列表查询
     *
     * @param contentInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "内容信息-分页列表查询")
    @ApiOperation(value="内容信息-分页列表查询", notes="内容信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ContentInfo contentInfo,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
        String contentTitle = null;
        if(!StringUtil.isEmpty(contentInfo.getContentTitle())){
            contentTitle = contentInfo.getContentTitle();
        }
        QueryWrapper<ContentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time").eq("del_flag",0).in("is_release",'1','3',"2");
        if(!StringUtil.isEmpty(contentTitle)){
            queryWrapper.like("content_title",contentTitle);
        }
        int contentType = 0;
        if(null != contentInfo.getContentType()){
            contentType = contentInfo.getContentType().intValue();
        }
        if(0 != contentType){
            queryWrapper.like("content_type",contentType);
        }

        Page<ContentInfo> page = new Page<ContentInfo>(pageNo, pageSize);
        IPage<ContentInfo> pageList = conContentInfoService.page(page, queryWrapper);
        //查询是否同步到稿源库
        pageList.getRecords().stream().forEach(item->{
            QueryWrapper<ConContentTemplate> templateQueryWrapper = new QueryWrapper<>();
            templateQueryWrapper.eq("content_no",item.getContentNo());
            if(templateService.count(templateQueryWrapper)>0){
                item.setIsTemplate(1);
            }else{
                item.setIsTemplate(0);
            };
        });

        return Result.ok(pageList);
    }


    /**
     * 我的内容信息
     *
     * @param contentInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "内容信息-我的内容信息")
    @ApiOperation(value="内容信息-我的内容信息", notes="内容信息-我的内容信息")
    @GetMapping(value = "/myContentList")
    public Result<?> myContentList(ContentInfo contentInfo,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //查询这个人参与的所有步骤
        QueryWrapper<TaskWorkflowStep> stepQueryWrapper = new QueryWrapper<>();
        stepQueryWrapper.eq("deal_user_id",loginUser.getId());
        List<TaskWorkflowStep> stepList = stepService.list(stepQueryWrapper);
        List<String> inList = new ArrayList<>();
        stepList.stream().forEach(item->{
            inList.add(item.getTaskNo());
        });
        QueryWrapper<ContentInfo> contentInfoQueryWrapper = new QueryWrapper<>();
        contentInfoQueryWrapper.in("task_id",inList).eq("del_flag",0).in("is_release",'1','3',"2").orderByDesc("create_time");
        Page<ContentInfo> page = new Page<ContentInfo>(pageNo, pageSize);
        IPage<ContentInfo> pageList =null;
        if(null != inList && inList.size()>0){
             pageList = conContentInfoService.page(page, contentInfoQueryWrapper);
            //查询是否同步到稿源库
            pageList.getRecords().stream().forEach(item->{
                QueryWrapper<ConContentTemplate> templateQueryWrapper = new QueryWrapper<>();
                templateQueryWrapper.eq("content_no",item.getContentNo());
                if(templateService.count(templateQueryWrapper)>0){
                    item.setIsTemplate(1);
                }else{
                    item.setIsTemplate(0);
                };
            });
        }else{
            page.setTotal(0);
            page.setRecords(new ArrayList<>());
        }

        return Result.ok(null != pageList?pageList:page);
    }



    /**
     * 发布内容到咨询app
     *
     * @param req
     * @return
     */
    @AutoLog(value = "内容信息-发布内容到咨询app")
    @ApiOperation(value="内容信息-发布内容到咨询app", notes="内容信息-发布内容到咨询app")
    @PostMapping(value = "/publishContent")
    public Result<?> publishContent(@RequestBody Map<String,Object> publish,
                                   HttpServletRequest req) {
        //查询任务信息
        TaskInfoBase taskInfoBase = operationService.queryTaskInfoByTaskNo(publish.get("taskNo").toString());
        //保存发布信息
        Map<String,Object> publishInfo = (Map<String,Object>)publish.get("publishInfo");
        operationService. savePublish(taskInfoBase,publishInfo);

        QueryWrapper<ContentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_id",publish.get("taskNo").toString()).last(" limit 1");
        ContentInfo contentInfo = conContentInfoService.getOne(queryWrapper);

        ContentGoto contentGoto = new ContentGoto();
        contentGoto.setId(UUIDGenerator.generate());
        contentGoto.setContent_id(contentInfo.getContentNo());
        contentGoto.setDest(3);
        contentGotoService.save(contentGoto);
        return Result.ok();
    }


    @AutoLog(value = "内容信息-分页列表查询")
    @ApiOperation(value="内容信息-分页列表查询", notes="内容信息-分页列表查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(
                                   @RequestParam(name="taskNo") String taskNo,
                                   HttpServletRequest req) {

        QueryWrapper<ContentInfo> contentInfoQueryWrapper = new QueryWrapper<>();
        contentInfoQueryWrapper.eq("task_id",taskNo).last(" limit 1");
        return Result.ok(conContentInfoService.getOne(contentInfoQueryWrapper));
    }

        /**
     * 删除内容
     *
     * @param req
     * @return
     */
    @AutoLog(value = "内容信息-删除内容")
    @ApiOperation(value="内容信息-删除内容", notes="内容信息-删除内容")
    @PostMapping(value = "/delete")
    public Result<?> delete(@RequestBody ConContentTemplate template,
                                    HttpServletRequest req) {
        //根据内容查询发布情况
        String contentNo = template.getContentNo();
        QueryWrapper<ContentGoto> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("content_id",contentNo);
        List<ContentGoto> gotoList =  contentGotoService.list(queryWrapper);
        if(gotoList == null || gotoList.size()  == 0){
            //可以删除
            UpdateWrapper<ContentInfo> contentInfoUpdateWrapper = new UpdateWrapper<>();
            contentInfoUpdateWrapper.eq("content_no",contentNo);
            contentInfoUpdateWrapper.set("del_flag","1");
            conContentInfoService.update(contentInfoUpdateWrapper);
            return Result.OK("删除成功");
        }else{
            //组装错误信息
            String msg = "删除失败，该文章已经";
            for(ContentGoto tempGoto : gotoList){
                if(tempGoto.getDest() == 1){
                    msg+="同步到模板，";
                }else if(tempGoto.getDest() == 2){
                    msg+="发布到官网，";
                }else if(tempGoto.getDest() == 3){
                    msg+="发布到APP，";
                }else if(tempGoto.getDest() == 4){
                    msg+="发布到第三方平台，";
                }
            }
           return  Result.error(msg.substring(0,msg.length()-1));
        }
    }

}
